import colorsys
import re
import time

import PIL.Image as Image
import cv2
import mysql.connector
import paddleocr

from sync_with_mysql_module import \
    save_trip_code_to_sql, save_health_code_to_sql, save_nucleic_acid_to_sql

table_engine = paddleocr.PPStructure(show_log=False)  # 引擎配置



def trip_code(information, filename):
    if recent_region := re.search(r'您于前7天内到达或途经：\s*(\S*)', information, re.M | re.I):
        recent_region = recent_region.group()
    if phone := re.search(r'(\d{3})(\*+)(\d{4})', information, re.M | re.I):
        phone = phone.group()
    if update_time := re.search(r'(更新于：)(\s*(\S*))', information, re.M | re.I):
        update_time = update_time.group(2)
        update_time = update_time[:10] + ' ' + update_time[10:]
    if update_time and phone and recent_region:
        save_trip_code_to_sql(recent_region, phone, update_time, filename)


def health_code(information, pic_main_rgb):
    if identity := re.search(r'\d{17}\d|x|X', information, re.M | re.I):
        identity = identity.group()
        save_health_code_to_sql(identity, rgb_to_rgy(pic_main_rgb))


def nucleic_acid_report(information):
    name = ""
    if identity := re.search(r'\d{17}\d|x|X', information, re.M | re.I):
        identity = identity.group()
        identity_index = information.split().index(identity)
        name = information.split()[identity_index - 1]
    if check_time := re.search(r'(检测时间：)(\s*(\S*))', information, re.M | re.I):
        check_time = check_time.group(2)
        check_time = check_time[:10] + ' ' + check_time[-8:]
    if organization := re.search(r'(检测机构：)(\s*(\S*))', information, re.M | re.I):
        organization = organization.group(2)
    if nucleic_report := re.search(r'(\S性)', information, re.M | re.I):
        nucleic_report = nucleic_report.group()
    if identity and check_time and organization and nucleic_report:
        save_nucleic_acid_to_sql(name, identity, nucleic_report, check_time, organization)


def get_dominant_color(image):
    max_score = 0.0001
    dominant_color = None
    for count, (r, g, b) in image.getcolors(image.size[0] * image.size[1]):
        saturation = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)[1]
        y = min(abs(r * 2104 + g * 4130 + b * 802 + 4096 + 131072) >> 13, 235)
        y = (y - 16.0) / (235 - 16)
        if y > 0.9:
            continue
        score = (saturation + 0.1) * count
        if score > max_score:
            max_score = score
            dominant_color = (r, g, b)
    return dominant_color


def rgb_to_rgy(rgb_color):
    # r最高，g和b大致相等且数值偏小，那么这个颜色就是“红色”。
    if rgb_color[0] > rgb_color[1] and rgb_color[0] > rgb_color[2] and abs(rgb_color[1] - rgb_color[2]) < 16 and \
            (rgb_color[1] + rgb_color[2]) >> 1 < 32:
        return "2"
    # r最高，g更接近b， b最低。那么这个颜色就是“偏黄的红色”。
    elif rgb_color[0] > rgb_color[1] > rgb_color[2] and abs(rgb_color[0] - rgb_color[1]) > \
            abs(rgb_color[2] - rgb_color[3]):
        return "1"
    # r最高，g更接近r， b最低。那么这个颜色就是“接近黄色”，如果abs(r-g)==0那么就是“黄色”。
    elif rgb_color[0] > rgb_color[1] > rgb_color[2] and abs(rgb_color[0] - rgb_color[1]) < \
            abs(rgb_color[2] - rgb_color[3]):
        return "1"
    # g最高，r和b大致相等且数值偏小，那么这个颜色就是“绿色”。
    elif rgb_color[1] > rgb_color[0] and rgb_color[1] > rgb_color[2] and abs(rgb_color[0] - rgb_color[2]) < 16 and \
            (rgb_color[0] + rgb_color[2]) >> 1 < 128:
        return "0"
    return "-1"


def start(filename, date=time.strftime(r"/%Y/%m/%d/", time.localtime())):
    img = cv2.imread("upload" + date + filename)
    results = table_engine(img)
    pic_main_rgb = get_dominant_color(Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)))

    all_information = ""
    for result in results:
        result.pop('img')
        for line in result["res"]:
            all_information += line["text"] + " "
    # print("%s\n %s" % (all_information, filename))
    classify(all_information, pic_main_rgb, filename)


def classify(information, pic_main_rgb, filename=None):
    trip_feature = re.search(r'请收下绿色行程卡|(\d{3})(\*+)(\d{4})', information, re.M | re.I)
    health_feature = re.search(r'健康码出示|各地健康码服务热线|疫苗接种查询|健康状况核验', information, re.M | re.I)
    nucleic_acid_feature = re.search(r'核酸检测信息|核酸采样标识|核酸检测结果|检测时间：\s*(\S*)', information, re.M | re.I)
    if trip_feature:
        trip_code(information, filename)
    elif health_feature:
        health_code(information, pic_main_rgb)
    elif nucleic_acid_feature:
        nucleic_acid_report(information)
    else:
        pass


if __name__ == '__main__':
    while True:
        db = mysql.connector.connect(host='127.0.0.1', user='root', passwd='123456', database='ruoyi_vue')
        cursor = db.cursor()
        path = time.strftime(r"/%Y/%m/%d/", time.localtime())
        cursor.execute("select * from files where has_checked=0")
        task_list = cursor.fetchall()
        if not task_list:
            time.sleep(30)
            db.close()
        else:
            for task in task_list:
                start(task[4])
                cursor.execute("update files set has_checked=1 where files='{task_name}'".format(task_name=task[4]))
                db.commit()
            db.close()
